package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Splitter;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


@Slf4j
public class TranslatorUtil {


    private static final String API_SECRET_KEY = "f65a2248aa9c29a62ffc7edef75d472f.hDMhJd1PugdgK2zH";


    private static final ClientV4 client = new ClientV4.Builder(API_SECRET_KEY).build();

    static String prompt =
            "英汉互译，只提供最好的一个翻译结果，自动识别我给你的句子的国别（如果是英语，就翻译成中文，反之，翻译成英文），不要注释，不要回答任何无关内容。开始翻译下面内容：";
    private static final String requestIdTemplate = "mindmax-%d";


    public static String translate(String text) {
        log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        log.info("$$$$$ to translate text:{}", text);
        StopWatch watch =  StopWatch.createStarted();
        List<ChatMessage> messages    = new ArrayList<>();
        ChatMessage       chatMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt);
        messages.add(chatMessage);
        messages.add(new ChatMessage(ChatMessageRole.USER.value(), text));
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        if (null == invokeModelApiResp || !invokeModelApiResp.isSuccess()) {
            log.error("调用ChatGPT接口失败，请检查参数是否正确，错误信息：{}", Optional.ofNullable(invokeModelApiResp).map(ModelApiResponse::getMsg).orElse("响应为空"));
            return "";
        }
        String result = invokeModelApiResp.getData().getChoices().getFirst().getMessage().getContent().toString();
        result = result.trim();
        result = Splitter.on("\n").omitEmptyStrings().trimResults().splitToList(result).getFirst();
        log.info("$$$$$  translated result:{}", result);
        log.info("$$$$$  time elapsed = {} ms", watch.getTime());
        log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

        return result;
    }

}
